package cn.xawl.gulimall.auth.controller;

import cn.xawl.common.utils.HttpUtils;
import cn.xawl.common.utils.R;
import cn.xawl.gulimall.auth.feign.MemberFeign;
import cn.xawl.common.vo.MemberVo;
import cn.xawl.gulimall.auth.vo.WeiboUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lh
 * @create 2020-10-31 17:27
 *
 * 处理第三方登录
 **/
@Controller
@RequestMapping("oauth2")
public class OAuth2Controller {

    @Autowired
    private MemberFeign memberFeign;

    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> queryMap = new HashMap<>();
        queryMap.put("client_id", "2001277643");
        queryMap.put("client_secret", "1ae009f308ecd7111c551a343d644f1e");
        queryMap.put("grant_type", "authorization_code");
        queryMap.put("redirect_uri", "http://auth.gulimall.com/oauth2/weibo/success");
        queryMap.put("code", code);

        //为微博验证服务器发送请求，获取access Token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<>(),
                queryMap,
                "");
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了Access Token
            String resEntity = EntityUtils.toString(response.getEntity()); //获取响应的json字符串

            WeiboUser weiboUser = JSON.parseObject(resEntity, WeiboUser.class);

            System.out.println(weiboUser);
            //调用远程用户服务，将当前微博用户添加或者更新用户
            R r = memberFeign.login(weiboUser);
            if ((int)r.get("code") == 0) {
                MemberVo data = r.getData(new TypeReference<MemberVo>() {});
                System.out.println(data);
                session.setAttribute("userInfo", data);
                //TODO session作用域问题
                //TODO 序列化不使用JDK序列化，使用ｊｓｏｎ
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            //未获取到access token，登陆失败
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }

}
